package algorithm_optimal_solution.LinkedList;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

//向有序的环形单链表中插入新节点：设置pre节点和cur节点，满足条件num大于pre节点的值并且小于cur节点的值插入即可。
// 记得判断num的节点是否是头节点的情况。
public class InsertNodeToRingAsc {

    static class Node{
        private int value;
        private Node node;

        public Node(int value){
            this.value = value;
        }

        public Node(int value,Node node){
            this.value = value;
            this.node = node;
        }

        public int getValue() {
            return value;
        }

        public void setValue(int value) {
            this.value = value;
        }

        public Node getNode() {
            return node;
        }

        public void setNode(Node node){
            this.node = node;
        }
    }

    public void insertNum(Node head,int num){
        Node node = new Node(num);
        if(head == null){
            node.setNode(node);
        }
        Node cur = head.getNode();
        Node pre = head;
        while(cur != head){
            if(num >= pre.getValue() && num <= cur.getValue()){
                break;
            }
            pre = cur;
            cur = cur.getNode();
        }
        pre.setNode(node);
        node.setNode(cur);
        node = num > head.getValue() ? head : node;
        StringBuilder sb = new StringBuilder();
        sb.append(node.getValue()).append(" ");
        head = node.getNode();
        while(head != node){
            sb.append(head.getValue()).append(" ");
            head = head.getNode();
        }
        System.out.print(sb);
    }

    public static void main(String[] args)throws IOException {
        BufferedReader scanner = new BufferedReader(new InputStreamReader(System.in));
        int len = Integer.parseInt(scanner.readLine());
        String[] numbers = scanner.readLine().split(" ");
        Node node = new Node(Integer.parseInt(numbers[len - 1]),null);//环形单链表
        Node currentNode = node;
        for(int i = len - 2;i >= 0;i--){
            node = new Node(Integer.parseInt(numbers[i]),node);
        }
        currentNode.setNode(node);
        int num = Integer.parseInt(scanner.readLine());
        new InsertNodeToRingAsc().insertNum(node,num);
    }
}
